
package at.fhj.ase.clientarch.server.db.dao.impl;

import java.sql.Timestamp;
import java.util.List;

import javax.persistence.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import at.fhj.ase.clientarch.common.util.CollectionUtil;
import at.fhj.ase.clientarch.common.util.CommonUtil;
import at.fhj.ase.clientarch.server.db.dao.HardwareDataDAO;
import at.fhj.ase.clientarch.server.db.hibernate.entities.EntityHardwareData;

/**
 * @author cja, sfe | www.fh-joanneum.at | Client Architectures and Design
 */
public class HardwareDataDAOImpl extends GenericDAOImpl<EntityHardwareData, Long> implements HardwareDataDAO {
  private final Logger logger = LoggerFactory.getLogger(getClass().getName());

  /** Constructor - make this class only usable to {@link DatabaseController} */
  HardwareDataDAOImpl() {
    super();
  }

  @Override
  public List<EntityHardwareData> findByTimestamp(final Timestamp start, final Timestamp end) {
    // make sure that there are no useless database operations performed
    if (CommonUtil.areNull(start, end)) {
      return null;
    }

    Query query = getEntityManager().createQuery("FROM EntityHardwareData h WHERE h.timestamp > ?1 and h.timestamp < ?2");
    query = query.setParameter(1, start);
    query = query.setParameter(2, end);

    List<EntityHardwareData> hwDataList = null;
    try {
      hwDataList = query.getResultList();
      if (CollectionUtil.isNullOrEmpty(hwDataList)) {
        return null;
      }
    } catch (Exception e) {
      logger.warn("Query unsuccessful: " + e, e);
    }

    return hwDataList;
  }

  @Override
  public void insertList(final List<EntityHardwareData> dataList) {
    CollectionUtil.checkNullOrEmpty(dataList);

    // do everything within one transaction
    begin();
    for (EntityHardwareData ehw : dataList) {
      logger.debug("Trying to insert: " + ehw);
      getEntityManager().persist(ehw);
    }
    commit();
  }
}
